/*
 * @Author: yanjikun
 * @Date: 2022-04-21 11:18:15
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-12 15:36:56
 * @Description: file content
 */

import { error } from '@/utils/log'
import { isEmpty } from 'lodash'
import { nextTick, onMounted, Ref, ref, SetupContext, unref, watch } from 'vue'
import DynamicTable from '../..'
import type { DynamicTableInstance, DynamicTableProps } from '../dynamic-table'

export const useTable = (props?: DynamicTableProps) => {
  const dynamicTableRef = ref<DynamicTableInstance>({} as DynamicTableInstance)
  const getTableInstance = async () => {
    await nextTick()
    const table = unref(dynamicTableRef)
    if (isEmpty(table)) {
      error('未获取到表格实例!')
    }
    return table
  }

  watch(
    () => props,
    () => {
      props &&
        onMounted(async () => {
          ;(await getTableInstance())?.setProps(props)
        })
    },
    {
      immediate: true,
      deep: true,
    },
  )
  const methods = new Proxy<Ref<DynamicTableInstance>>(dynamicTableRef, {
    get(target, key) {
      if (Reflect.has(target, key)) {
        return unref(target)
      }
      if (Reflect.has(target.value, key)) {
        return target.value[key]
      }
      return async (...rest) => {
        const table = await getTableInstance()
        table?.[key](...rest)
      }
    },
  })

  const DynamicTableRender = (
    comProps: Partial<DynamicTableProps>,
    { attrs, slots }: SetupContext,
  ) => {
    return (
      <DynamicTable
        ref={dynamicTableRef}
        {...{ ...attrs, ...props, ...comProps }}
        v-slots={slots}
      ></DynamicTable>
    )
  }
  return [DynamicTableRender, unref(methods)] as const
}
